package app.dws;

import app.BaseAppV1;
import bean.CommentCountBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import util.AtguiguUtil;

import java.time.Duration;

public class DwsCourseComment extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsCourseComment().init(
                4010,
                1,
                "DwsCourseComment",
                Constant.TOPIC_DWD_COURSE_COMMENT
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        // 转成POJO类
        SingleOutputStreamOperator<CommentCountBean> CommentBeanStream = CommentToPojo(stream);

        // 判断好评
        SingleOutputStreamOperator<CommentCountBean> UniqueStream = UniqueComment(CommentBeanStream);

        // 开窗聚合
        SingleOutputStreamOperator<CommentCountBean> CommentStream = windowAndAgg(UniqueStream);

        // 写出
        CommentStream
                .map(bean -> JSON.toJSONString(bean))
                .print();
    }

    private SingleOutputStreamOperator<CommentCountBean> windowAndAgg(SingleOutputStreamOperator<CommentCountBean> uniqueStream) {
        return uniqueStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<CommentCountBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                (bean, ts) -> bean.getTs() * 1000
                        )
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(
                        new ReduceFunction<CommentCountBean>() {
                            @Override
                            public CommentCountBean reduce(CommentCountBean bean1,
                                                           CommentCountBean bean2) throws Exception {
                                bean1.setCommentCount(bean1.getCommentUserCount() + bean2.getCommentUserCount());
                                bean1.setHighCommentCount(bean1.getHighCommentCount() + bean2.getHighCommentCount());
                                bean1.setGradeCount(bean1.getGradeCount() + bean2.getGradeCount());
                                bean1.setCommentCount(bean1.getCommentCount() + bean2.getCommentCount());

                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<CommentCountBean, CommentCountBean, TimeWindow>() {
                            @Override
                            public void process(Context context,
                                                Iterable<CommentCountBean> iterable,
                                                Collector<CommentCountBean> collector) throws Exception {
                                CommentCountBean bean = iterable.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));
                                bean.setCurDate(AtguiguUtil.toDate(context.window().getStart()));

                                collector.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<CommentCountBean> UniqueComment(SingleOutputStreamOperator<CommentCountBean> commentBeanStream) {
        return commentBeanStream
                .keyBy(CommentCountBean::getUserId)
                .process(new KeyedProcessFunction<String, CommentCountBean, CommentCountBean>() {

                    private ValueState<String> uniqueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        uniqueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("UniqueState",String.class));
                    }

                    @Override
                    public void processElement(CommentCountBean commentCountBean,
                                               Context context,
                                               Collector<CommentCountBean> collector) throws Exception {
                        if (uniqueState.value() == null) {
                            commentCountBean.setCommentCount(1L);
                            uniqueState.update("true");
                        }
                        collector.collect(commentCountBean);
                    }
                });
    }

    private SingleOutputStreamOperator<CommentCountBean> CommentToPojo(DataStreamSource<String> stream) {

        return stream
                .map(json -> {
                    JSONObject obj = JSON.parseObject(json);

                    // user用来分组判断独立用户数
                    String user_id = obj.getString("user_id");

                    long review_stars = Long.parseLong(obj.getString("review_stars"));

                    long ts = Long.parseLong(obj.getString("ts"));

                    // 判断是否好评
                    long HighCommentCount = 0L;
                    if (obj.getString("review_stars") == "5") {
                        HighCommentCount = 1L;
                    }

                    return new CommentCountBean(
                            "",
                            "",
                            "",
                            0L,
                            1L,
                            HighCommentCount,
                            review_stars,
                            "",
                            ts
                    );
                });
    }
}
